// pages/commodity/confirmOrder/index.js
import {queryAddress,saveOrder,unionpay,deleteCart} from '../../../utils/api/index'
var app = getApp();
const imgUrl=app.globalData.imgUrl
Page({

  /**
   * 页面的初始数据
   */
  data: {
    number:1,
    imgUrl:imgUrl,
    userId:app.globalData.userId,
    addressData:null,//收货地址
    confirmOrderList:[],
    totalMoney:0,//总价
    remarks:[],//备注
    orderId:[],//订单Id
    prompt:false,
    invoiceData:null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      userId:app.globalData.userId,
    })
    this.getShopInfor()
    if(app.globalData.address!=null&&app.globalData.address!=''){
      this.setData({
        addressData:app.globalData.address
      })
    }else{
      this.getQueryAddress()
    }
  },
 //获取收货地址
 getQueryAddress:function(){
  const that=this
  var params={
    userId:app.globalData.userId,
  }
  wx.showLoading({
    title: '加载中....',
      mask:true 
  })
  queryAddress(params).then(res=>{
    if(res.status==200){
      var data=null
      res.data.forEach(v => {
        if(v.status==1){
          data=v
        }
      });
      if(data==null&&res.data.length>0){
        data=res.data[0]
      }
      that.setData({
        addressData:data
      })
    }else{
      wx.showToast({
        title:res.msg,
        icon: 'none',
        duration: 1500,
      })
    }
    wx.hideLoading()
  })
},
// 切换地址
getAddress:function(){
  if(this.data.addressData!=null&&this.data.addressData!=''){
    wx.navigateTo({
      url: '/pages/user/setUp/harvestAddress/index',
    });    
  }else{
    wx.navigateTo({
      url: '/pages/user/setUp/addAddress/index?type=add',
    });
  }
},
//获取商品
getShopInfor:function(){
  var confirmOrderList=app.globalData.confirmOrder
  var money=0,courierFee=0,remarks=[]
  var remarksList={}
    confirmOrderList.forEach(v=>{
      courierFee+=v.courierFee||0
      var sellerId=v.sellerId
          remarksList[sellerId]=''
      if(v.goods!=null&&v.goods.length>0){
        v.goods.forEach(list=>{
          money+=list.cartPrice*list.cartNum
        })      
      }        
    })
    money+=courierFee
    this.setData({
      remarks:remarksList,
      totalMoney:money.toFixed(2),
      confirmOrderList:confirmOrderList
    })
},
//备注
remarks:function(event){
  var sellerid=event.currentTarget.dataset.sellerid
  for(var arr in this.data.remarks){
    if(arr==sellerid){
      this.data.remarks[arr]=event.detail.value
    }
  }

  this.setData({
    remarks:this.data.remarks
  })
},
//减
less:function(event){
  var cartid=event.currentTarget.dataset.cartid
  var carList=this.data.confirmOrderList
  var money=0,courierFee=0
  carList.forEach(v=>{
    courierFee+=v.courierFee
    if(v.goods!=null&&v.goods.length>0){
      v.goods.forEach(list=>{
        if(list.cartId==cartid){
          if(list.cartNum<=1){        
            wx.showToast({
              title:'至少有一个商品',
              icon: 'none',
              duration: 1500,
            })
            money+=list.cartPrice*list.cartNum        
          }else{
            list.cartNum--
            money+=list.cartPrice*list.cartNum           
          }
        }else{
         money+=list.cartPrice*list.cartNum
        }
      })      
    }        
  })
  money+=courierFee
  this.setData({
    totalMoney:money.toFixed(2),
    confirmOrderList:carList
  })
},
  //加
plus:function(event){
  var cartid=event.currentTarget.dataset.cartid
  var carList=this.data.confirmOrderList
  var money=0,courierFee=0
  carList.forEach(v=>{
    courierFee+=v.courierFee
    if(v.goods!=null&&v.goods.length>0){
      v.goods.forEach(list=>{
        if(list.cartId==cartid){
          if(list.cartNum>=list.stockNum){
            money+=list.cartPrice*list.cartNum
          wx.showToast({
            title:'以达到最大商品库存',
            icon: 'none',
            duration: 1500,
          })
          }else{
          
          list.cartNum++
          money+=list.cartPrice*list.cartNum
          }
        }else{
        money+=list.cartPrice*list.cartNum
        } 
      })
    }        
  })
  money+=courierFee
  this.setData({
    totalMoney:money.toFixed(2),
    confirmOrderList:carList
  })
},

getprompt:function(){
  this.setData({
    prompt:!this.data.prompt
  })
},
//生成订单
getSaveOrder:function(){
  const that=this
  var data=this.data.confirmOrderList
  var sellerId=[],freight=[],integral=[],type=[],body=[],orderGoodsJson=[],ids=[]//商家Id,运费,积分,订单类型,订单详情,商品列表json,购物车Id
  data.forEach(v=>{  
    sellerId.push(v.sellerId)
    integral.push(0)
    type.push(0)
    var shopList=[]
    var bodyList=[]
    v.goods.forEach(list=>{
      // freight.push(list.freightPrice)   
      bodyList.push(list.name+list.cartLabel+'*'+list.cartNum)
      ids.push(list.cartId)
      var goodelist={
          goodsId:list.goodsId,
          goodsTitle:list.name,
          goodsNum:list.cartNum,
          goodsLabel:list.cartLabel,
          goodsHeadImg:list.headImg,
          goodsNowPrice:list.cartPrice,
          status:0,
      }
      shopList.push(goodelist)
    })
    orderGoodsJson.push(JSON.stringify(shopList))
    body.push(bodyList.join(","))
  })

  var params={
    userId:app.globalData.userId,
    sellerId:sellerId.join("&"),
    integral:integral.join("&"),
    // freight:freight.join("&"),
    userName:this.data.addressData.name,
    phone:this.data.addressData.phone,
    pro:this.data.addressData.pro,
    city:this.data.addressData.city,
    area:this.data.addressData.area,
    address:this.data.addressData.address,
    lng:this.data.addressData.lng,
    lat:this.data.addressData.lat,
    type:type.join("&"),
    anonymous:0,
    body:body.join('&'),
    remarks:JSON.stringify(this.data.remarks),
    invoice:JSON.stringify(this.data.invoiceData),
    buyType:0,
    orderGoodsJson:orderGoodsJson.join('&'),
  }
  for(var attr in params){
    if(params[attr]===null||params[attr]===''){
      delete params[attr];
    }
  }
  // return false
  wx.showLoading({
    title: '加载中....',
    mask:true 
  })
  that.setData({
    prompt:false
  })
  saveOrder(params).then(res=>{
    if(res.status==200){
      var orderId=[]
      res.data.forEach(v=>{
        orderId.push(v.id)
      })
      this.setData({
        orderId:orderId
      })
     
      this.getUnionpay(ids.join(','))
    }else{
      wx.showToast({
        title:res.msg,
        icon: 'none',
        duration: 1500,
      })
    }
    
  })
},

//删除购物车商品
deleteshopCartn:function(ids){
  var params={
    ids:ids,
    userId:app.globalData.userId,
    type:0,
    status:0,
  }
  deleteCart(params).then(res=>{})
},

getUnionpay:function(ids){
  var that=this 
  var params={
    openid:app.globalData.openId,
    orderId:this.data.orderId.join(',')
  }
  wx.showLoading({
    title: '加载中....',
      mask:true 
  })
  unionpay(params).then(res=>{
    if(res.status==200){
      this.deleteshopCartn(ids)
      var data=JSON.parse(res.data)
      console.log(data)
      if(data.errCode=='SUCCESS'){
        app.globalData.confirmOrder=null
        var respStr=JSON.parse(data.respStr)
        wx.requestPayment({
          timeStamp:respStr.miniPayRequest.timeStamp,     // 1490840662，时间戳
          nonceStr:respStr.miniPayRequest.nonceStr,    // 5K8264ILTKCH16CQ2502SI8ZNMTM67VS，随机字符串不长于32位
          package:respStr.miniPayRequest.package,    
          signType:respStr.miniPayRequest.signType,  // 签名算法类型，默认MD5，支持HMAC-SHA256和MD5
          paySign:respStr.miniPayRequest.paySign,    // 签名,假设已拼接，详细签名格式见下文
          // timeStamp:'1591947016',     // 1490840662，时间戳
          // nonceStr:'45817dd041844316adfcef6a2852f2ab',    // 5K8264ILTKCH16CQ2502SI8ZNMTM67VS，随机字符串不长于32位
          // package:'prepay_id=wx121530159589964755ed1fed1086993700',    
          // signType: 'RSA',  // 签名算法类型，默认MD5，支持HMAC-SHA256和MD5
          // paySign:'hs0H56mZ+nB+0LZAPbWwVdamII1f8EMdaxkLMkX8gCc+xUCzwlbXihNPNrsuz1tMi8CHXWEqwSyyHQt8YOSrAmOdpms+C71mWr91OtufZliCYbWAA/pZvqKW6oUd/SSRJY0N+W0K1eyZG5rbwvRI2kldFmiAOHuDBxmrMWZS+5EkZ1sg2eOx1VlDBNgsTwETxje4FKUcNs/9tElEH2bEcc0OKb/I7ANmHWCvA7A68gFrJ50/kavD3xZ+yPPzdfppILtzJ66rVusO+bYB7cNVAXOP6guObI+ETMK0xwZYQ6htfqY1P7gxyq12u7gv9lthJR2jloSrOmbTQ67iqTpxwg==',    // 签名,假设已拼接，详细签名格式见下文
          success: function (res) {
            wx.redirectTo({
              url: "/pages/payStatus/paysuccess/index"
            });
          },
          fail: function (res) {
            wx.redirectTo({
              url: "/pages/payStatus/payfailure/index"
            });
          },
          complete: function (res) {
          }      
        })
      }else{
        var respStr=JSON.parse(data.respStr)
        wx.showToast({
          title:respStr.errMsg,
          icon: 'none',
          duration: 1500,
        })
      }
      
    }else{
      wx.showToast({
        title:res.msg,
        icon: 'none',
        duration: 1500,
      })
    }
    // wx.hideLoading()
  })
},
//设置发票
invoice:function(event){
  var sellerid=event.currentTarget.dataset.sellerid
  wx.navigateTo({
    url: "/pages/commodity/invoice/index?sellerid="+sellerid+"&invoiceData="+JSON.stringify(this.data.invoiceData)
  });
},
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    app.globalData.address=null
    // app.globalData.confirmOrder=null
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    app.globalData.address=null
    // app.globalData.confirmOrder=null
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})